const { uploadImage } = require("../utils/index");
const extendArticle = require("../sequelize/extendArticle");
const extendArticleType = require("../sequelize/extendArticleType");
const { Op } = require("sequelize");

class Service {
	async list(query) {
		try {
			const pageNum = parseInt(query.pageNum) || 1;
			const pageSize = parseInt(query.pageSize) || 10;

			const rows = await extendArticle.findAndCountAll({});
			return {
				code: 200,
				message: "ok",
				result: {
					list: await extendArticle.findAll({
						limit: pageSize,
						offset: (pageNum - 1) * pageSize,
					}),
					count: rows.count,
				},
			};
		} catch (err) {
			console.error(err);
			throw new Error(err);
		}
	}

	async getArticleByTypeAndKeyword(query) {
		try {
			const where = {
				status: 1
			};
			if (query.keyword) {
				where.title = {
					[Op.like]: `%${query.keyword}%`,
				};
			}
			if (query.typeId) {
				where.extendArticleTypeId = query.typeId;
			}
			return {
				code: 200,
				message: "ok",
				result: {
					list: await extendArticle.findAll({
						where,
						include: [
							{
								model: extendArticleType,
							},
						],
					}),
				},
			};
		} catch (err) {
			console.error(err);
			throw new Error(err);
		}
	}

	async getArticleDetailById(query) {
		try {
			const where = {
				status: 1
			};

			if (query.id) {
				where.id = query.id;
			}

			return {
				code: 200,
				message: "ok",
				result: await extendArticle.findOne({
					where,
					include: [
						{
							model: extendArticleType,
						},
					],
				}),
			};
		} catch (err) {
			console.error(err);
			throw new Error(err);
		}
	}

	async add(body) {
		try {
			await extendArticle.create({ ...body, createTime: new Date() });
			return {
				code: 200,
				message: "ok",
				result: {},
			};
		} catch (err) {
			console.error(err);
			throw new Error(err);
		}
	}

	async update(body) {
		try {
			await extendArticle.update(body, { where: { id: body.id } });
			return {
				code: 200,
				message: "ok",
				result: {},
			};
		} catch (err) {
			console.error(err);
			throw new Error(err);
		}
	}

	async del(id) {
		try {
			await extendArticle.destroy({
				where: {
					id,
				},
			});
			return {
				code: 200,
				message: "ok",
				result: {},
			};
		} catch (err) {
			console.error(err);
			throw new Error(err);
		}
	}

	async upload(req, res) {
		try {
			const imgName = await uploadImage(req);
			return {
				code: 200,
				message: "ok",
				result: imgName,
			};
		} catch (err) {
			console.error(err);
			throw new Error(err);
		}
	}
}

module.exports = new Service();
